/**
 * @Project TMHSC
 * @Author Tran Manh Hung
 * @Email: hungtmit@gmail.com | tmh@xwebgate.com
 * @Copyright © 2011 TMH. All rights reserved
 * @Createdate Jan 31, 2011
 * @Createtime 9:57:36 PM
 */

package com.tmh.study.aASA
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * Spring particles :D. Collision using grid
	 */
	public class NodeGardenGrid extends Sprite
	{
		private var particles:Vector.<DisplayObject>;

		private var numParticles:uint = 100;

		private var minDist:Number = 50;

		private var springAmount:Number = .001;

		private var grid:CollisionGrid;

		public function NodeGardenGrid()
		{
			init();
		}

		private function init():void
		{
			grid = new CollisionGrid(stage.stageWidth, stage.stageHeight, 50);
			particles = new Vector.<DisplayObject>();

			for (var i:int = 0; i < numParticles; i++)
			{
				var particle:Ball = new Ball(10);
				particle.x = Math.random() * stage.stageWidth;
				particle.y = Math.random() * stage.stageHeight;
				particle.vx = Math.random() * 6 - 3;
				particle.vy = Math.random() * 6 - 3;
				addChild(particle);
				particles.push(particle);

				addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			}
		}

		private function enterFrameHandler(event:Event):void
		{
			graphics.clear();

			for (var i:int = 0; i < numParticles; i++)
			{
				var particle:Ball = particles[i] as Ball;
				particle.x += particle.vx;
				particle.y += particle.vy;

				if (particle.x > stage.stageWidth - particle.radius)
				{
					particle.x = particle.radius;
				}
				else if (particle.x < particle.radius)
				{
					particle.x = stage.stageWidth - particle.radius;
				}
				else if (particle.y > stage.stageHeight - particle.radius)
				{
					particle.y = particle.radius;
				}
				else if (particle.y < particle.radius)
				{
					particle.y = stage.stageHeight - particle.radius;
				}
			}

			grid.check(particles);
			var checks:Vector.<DisplayObject> = grid.checks;
			var numChecks:int = checks.length;

			for (i = 0; i < numChecks; i += 2)
			{
				var partA:Ball = checks[i] as Ball;
				var partB:Ball = checks[i + 1] as Ball;
				spring(partA, partB);
			}
		}

		private function spring(partA:Ball, partB:Ball):void
		{
			var dx:Number = partB.x - partA.x;
			var dy:Number = partB.y - partA.y;
			var dist:Number = Math.sqrt(dx * dx + dy * dy);

			if (dist < minDist)
			{
				graphics.lineStyle(1, 0xffffff, 1 - dist / minDist);
				graphics.moveTo(partA.x, partA.y);
				graphics.lineTo(partB.x, partB.y);

				var ax:Number = dx * springAmount;
				var ay:Number = dy * springAmount;

				partA.vx += ax;
				partA.vy += ay;
				partB.vx -= ax;
				partB.vy -= ay;
			}
		}
	}
}